package org.execute.tool.excel处理.对象转为excel;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class GenericExcelExporterUtil {
    /*
     * 将list对象转为Excel 并且发送
     */
    public static <T> void exportToExcel(List<T> dataList, HttpServletResponse response) throws IOException {
        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet("Data");

        if (dataList.isEmpty()) {
            throw new IllegalArgumentException("Data list cannot be empty for export.");
        }

        // 获取对象的类类型，假设所有对象类型相同
        Class<?> clazz = dataList.get(0).getClass();
        Field[] fields = clazz.getDeclaredFields();
        Method[] methods = clazz.getMethods();
//        for (Method method : methods) {
//            System.out.println("方法名: " + method.getName());
//        }
//        for (Field field : fields) {
//            System.out.println("属性名: " + field.getName());
//        }
        List<Field> fieldList = new ArrayList<>(Arrays.asList(fields));
        fieldList.removeIf(field -> field.getName().equals("serialVersionUID"));


        // 创建表头
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < fieldList.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(fieldList.get(i).getName());
        }

        // 填充数据
        for (int i = 0; i < dataList.size(); i++) {
            Row row = sheet.createRow(i + 1);
            T object = dataList.get(i);
            for (int j = 0; j < fieldList.size(); j++) {
                Field field = fieldList.get(j);
                String methodName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
                try {
                    Method method = clazz.getMethod(methodName);
                    Object value = method.invoke(object);
                    Cell cell = row.createCell(j);
                    if (value!= null) {
                        if (value instanceof String) {
                            cell.setCellValue((String) value);
                        } else if (value instanceof Integer) {
                            cell.setCellValue((Integer) value);
                        } else if (value instanceof Double) {
                            cell.setCellValue((Double) value);
                        } else if (value instanceof Boolean) {
                            cell.setCellValue((Boolean) value);
                        } else if (value instanceof java.util.Date) {
                            cell.setCellValue(((java.util.Date) value).toString());
                        } else {
                            cell.setCellValue(value.toString());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        // 设置响应头，以指示这是一个下载操作
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=exported_data.xlsx");

        // 将Excel内容写入响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }
}